package com.gilgamesh.im.handle.server;

import java.io.*;
import java.net.Socket;

/**
 * 获取监听之后就开启的线程处理类
 **/
public class MsgHandle implements Runnable {

    /**
    * 当前线程正在处理的客户端socket
    **/
    private Socket socket;

    public MsgHandle(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            /**
            * 从套接字中获取字节流对象
            **/
            InputStream inputStream = socket.getInputStream();
            /**
            * 将字节流装饰成字符流
            **/
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            /**
            * 获取对应客户端ip地址
            **/
            String ip  = socket.getInetAddress().getHostAddress();
            Integer port = socket.getPort();
            String msg;
            /**
            * 从字符流中读取整行
            **/
            while ((msg = reader.readLine()) != null) {
                System.out.println("来自"+ip+":"+port+"的消息: "+msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
